<template>
  <div class="app-container">
    <br>
    <el-form :model="query" ref="query" label-width="80px" style="width: 100%;">
      <el-row :gutter=10>
        <el-col :span=4 >
          <el-form-item label="库房" prop="jobId">
            <el-select style="width:100%" v-model="query.drugDepositoryId" placeholder="请选择">
              <el-option
                v-for="item in depositoryEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                @click.native="selectDrugDepositoryId(item.id)"
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=6 :offset=1>
          <el-button type="primary" @click="add">添加盘点</el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="50">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="盘点仓库" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.checkDepositoryName }}
        </template>
      </el-table-column>
      <el-table-column label="盘点人" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.checkUserName }}
        </template>
      </el-table-column>
      <el-table-column label="盘点日期" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.updatedTime }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="150" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusColorFilter">{{ scope.row.status | statusNameFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="操作" align="center" width="300" >
        <template slot-scope="scope">
          <el-button type="primary" v-if="scope.row.status != 0" :loading="toInfoBtnLoading"  @click="getInfo(scope.row)" size="small">详情</el-button>
          <el-button type="success" v-if="scope.row.status === 0" :loading="toInfoBtnLoading"  @click="getInfo(scope.row)" size="small">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="->, total, prev, pager, next"
      :total="this.total"
      :current-page="currentPage"
      :page-size="pageSize"
      @current-change="clickCurPage"
      >
    </el-pagination>
  <el-dialog title="盘点详情" :visible.sync="infoVisible" width="1500px">
    <h2>盘点信息</h2>
    <el-form ref="info" :model="info" label-width="80px">
      <el-row :gutter="10">
        <el-col :span=6>
          <el-form-item label="盘点仓库">
            <el-input v-model="info.drugCode" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span=6 >
          <el-form-item label="盘点日期">
              <el-input v-model="info.depositoryName" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span=6 >
          <el-form-item label="盘点人">
              <el-input v-model="info.depositoryName" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>
      
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  </div>
</template>

<script>
import { queryDepositoryNumList } from '@/api/drug'
import { getList as getStoreList, getAvailableDepositoryList } from '@/api/store'
import { getList as getCheckList, getInfo as getCheckInfo } from '@/api/checkRepository'
import { stringToDate } from '@/utils/dateUtil'

export default {
  name: "Check",
  filters: {
    statusColorFilter(status) {
      const statusMap = ['warning', 'primary', 'info']
      return statusMap[status]
    },
    statusNameFilter(status) {
      const statusMap = ['草稿', '已盘点待审核', '已审核']
      return statusMap[status]
    }
  },
  data() {
    const validatePlan = (rule, value, callback) => {
      if (!value) callback(new Error('请填写计划名称')) 
      else callback()
    }
    const validateType = (rule, value, callback) => {
      if (!value) callback(new Error('请选择类型'))
      else callback()
    }
    const validateDept = (rule, value, callback) => {
      if (!this.form.depository) callback(new Error('请选择部门'))
      else callback()
    }
    return {
      list: null,
      listLoading: true,
      toUpdateBtnLoading: false,
      toInfoBtnLoading: false,
      commitBtnLoading: false,
      currentPage: 1,
      pageSize: 10,
      total: 20,
      curIndex: -1,
      infoVisible: false,
      formVisible: false,
      dialogTitle: '',
      info: {},
      form: {},
      purchaseOrderList: [],
      typeEnum: ["集中", "临时"],
      depositoryEnum: [],
      suppliers: [],
      query: {},
      tagEnum: [{id: 1, name: '热销'},{id: 2, name: '促销'}],
      dugTypeTreeList: [],
      formRules: {
        plan: [{ required: true, trigger: 'blur', validator: validatePlan }],
        type: [{ required: true, trigger: 'blur', validator: validateType }],
        dept: [{ required: true, trigger: 'blur', validator: validateDept }],
      },
      searchValue: ''
    }
    
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getAvailableDepositoryList({optType: 5}).then(deptRes=> {
        console.log("deptRes", deptRes)
        this.depositoryEnum = deptRes.data
        if(this.depositoryEnum.length == 0) {
          this.listLoading = false
          return;
        }
        this.query.drugDepositoryId = this.depositoryEnum[0].id
        getCheckList({currentPage: this.currentPage, pageSize: this.pageSize, drugDepositoryId: this.query.drugDepositoryId}).then(res=> {
          console.log(res)
          this.list = res.data.records
          this.listLoading = false
        })
      })
    },
    clickCurPage(val){
      this.currentPage = val
      this.fetchData()
    },
    getInfo(row) {
      this.$router.push({name: "CheckPage", params: row});
    },
    calculateExpirationTime(form) {
      form.godownDrugList.forEach(godown=> {
        if(godown.productTime != undefined) {
          var productTime = stringToDate(godown.productTime)
          var productYear = productTime.getFullYear();
          var productMonth = productTime.getMonth();
          var expirationTime = stringToDate(godown.expirationTime)
          var expirationYear = expirationTime.getFullYear();
          var expirationMonth = expirationTime.getMonth();
          this.$set(godown, 'qualityTime', expirationMonth - productMonth + (expirationYear - productYear)*12)
        }
      })
    },
    cancel() {
      this.infoVisible = false
      this.formVisible = false
    },
    reset(){
      this.form = {}
    },
    search() {
      this.listLoading = true
      console.log(this.query.depositoryIds)
      var reqDepositoryIds = this.query.depositoryIds.map(item=> item).join(',')
      console.log(reqDepositoryIds)
      const reqBody = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          drugName: this.query.drugName,
          depositoryIds: reqDepositoryIds
      }
      queryDepositoryNumList(reqBody).then(response=>{
        console.log(response)
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    add() {
      if(this.query.drugDepositoryId == undefined) {
        this.$message.error('请选择库房')
        return
      }
      this.$router.push({ name: 'CheckPage', params: this.query})
    },
    selectDrugDepositoryId(id) {
      this.listLoading = true
      this.query.drugDepositoryId = id
      getCheckList({currentPage: this.currentPage, pageSize: this.pageSize, drugDepositoryId: this.query.drugDepositoryId}).then(res=> {
        console.log(res)
        this.list = res.data.records
        this.listLoading = false
      })

    },
  }
}

</script>

<style>
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
  .drug-input {
    width: 100%;
    display: inline-block;
    margin-right: 10px;
  }
  .drugs-item-title {
    line-height: 20px;
    text-align: center;
    background-color: #E4E7ED;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
  }
  .drugs-item {
    width: 140px;
    display: flex;
    flex-direction: column;
    margin-right: 20px;
  }
  .drug-name {
    width: 300px;
    word-wrap: break-word;
    margin-right: 20px;
    font-size: 15px;
    height: 58px;
    line-height: 58px;
  }
</style>